<?php
defined('BASEPATH') OR exit('No direct script access allowed');


class Order_service
{
	public function __construct()
	{
		$this->ci = & get_instance();
		$this->ci->load->model('Order_model');
		$this->ci->load->model('Orderbook_model');
		$this->ci->load->model('User_model');
		$this->ci->load->model('Product_model');
	}

	//sellerid,buyerid,item,scene,time,num,memo,linkman,linkway,begtime,endtime,seller_username,seller_nickname,buyer_username,buyer_nickname
	public function book()
	{
		$res = array('code'=>0, 'data'=>array());
		$config = array(
           	array(
                 'field'   => 'booked_userid', 
                 'label'   => '登录用户', 
                 'rules'   => 'trim|required'
            ),
            array(
                 'field'   => 'item', 
                 'label'   => '工作内容', 
                 'rules'   => 'trim|required'
            ),
//            	array(
//                  'field'   => 'scene', 
//                  'label'   => '工作场景', 
//                  'rules'   => 'trim|required'
//             ),  
            array(
                 'field'   => 'time', 
                 'label'   => '计价方式', 
                 'rules'   => 'trim|required'
            ),
            array(
                 'field'   => 'begtime', 
                 'label'   => '预订时间', 
                 'rules'   => 'trim|required'
            ),
        );

        $this->ci->form_validation->set_rules($config);

		if ($this->ci->form_validation->run() === TRUE)
		{
			$item = $this->ci->input->post('item');
			$scene = (int)$this->ci->input->post('scene');
			$time = $this->ci->input->post('time');
			$num = ( (int)$this->ci->input->post('num') == 0 )?1:(int)$this->ci->input->post('num');

			$buyerid = $this->ci->loginID;
			$buyer_usertype = $this->ci->loginUsertype;
			if(!$buyerid)
				$buyerid = (int)$this->ci->input->post('buyerid');
			$sellerid = _get_key_val( $this->ci->input->post('booked_userid'), true);
			if(!$sellerid)
			{
				$res['code'] = 201;
				$res['data']['error_messages'] = array('页面过期，请刷新页面后重新下单');
				return $res;
			}
			//被下单模特、化妆师、摄影师
			$oSeller = $this->ci->User_model->get_by_id($sellerid);
			//验证是否是自己对自己下单，或者机构对旗下艺人下单
			if ($sellerid == $buyerid)
			{
				$res['code'] = 203;
				$res['data']['error_messages'] = array('不能对自己下单');
				return $res;
			}
			if ($oSeller['insid'] == $buyerid)
			{
				$res['code'] = 204;
				$res['data']['error_messages'] = array('不能对自己旗下艺人下单');
				return $res;
			}
			
			$price = $this->ci->input->post('price');
			//内衣泳装、情趣内衣加收百分比
// 			$addPercentage = 0;
// 			$oProduct = $this->ci->Product_model->get_produdct_by_uist($sellerid, $item, $scene, $time);
// 			if($oProduct)
// 			{
// 			    $price = $oProduct['price'];
// 			    if ($oProduct['swimsuit'] > 0.1)
// 			        $addPercentage += $oProduct['swimsuit'];
// 			    if ($oProduct['appealsuit'] > 0.1)
// 			        $addPercentage += $oProduct['appealsuit'];
// 			}
			if(!$price)
				$price = $this->ci->config->item('workprice');
			$begtime=$this->ci->input->post('begtime');		//格式:2015-5-15

			$oSysKind = $this->ci->config->item('orderkind');
			$oSysItem = $this->ci->config->item('workitem');
			$oSysScene = $this->ci->config->item('workscene');
			$oSysTime = $this->ci->config->item('worktime');
			$no = date('YmdHis',time()).rand(1000,9999);
			$title = '工作:'.$oSysItem[$item];
			$title .= $scene?' 场景:'.$oSysScene[$scene]:'';
			$title .= $num.$oSysTime[$time];
			$o = array(
					'sellerid'=>$sellerid,
					'title'=>$title,
					'no'=>$no,
					'kind'=>$oSysKind['book'],
					'buyerid'=>$buyerid,
					'buyer_username'=>$this->ci->loginUserName,
					'buyer_nickname'=>$this->ci->loginNickName,
					'addtime'=>time(),
					'paystatus'=>0,
					'status'=>1,
					'reject'=>0,
					'op_userid'=>$buyerid,
					'op_username'=>$this->ci->loginUserName,
					'op_time'=>time(),
					'remark'=>$this->ci->input->post('remark'),
				);
			$oBook = array(
					'sellerid'=>$sellerid,
					'no'=>$no,
					'item'=>$item,
					'scene'=>$scene,
					'time'=>$time,
					'price'=>$price,
					'num'=>$num,
					'work_place'=>$this->ci->input->post('work_place'),
					'memo'=>$this->ci->input->post('memo'),
					'linkman'=>$this->ci->input->post('linkman'),
					'linkway'=>$this->ci->input->post('linkway'),
				);

			if(!isset($o['seller_username']) || !isset($o['seller_nickname']))
			{
				$oSeller = $this->ci->User_model->get_by_id($sellerid);
				if(!empty($oSeller))
				{
					$o['seller_username'] = $oSeller['username'];
					$o['seller_nickname'] = $oSeller['nickname'];
				}
			}

			if(!isset($o['buyer_username']) || !isset($o['buyer_nickname']))
			{
				$oBuyer = $this->ci->User_model->get_by_id($buyerid);
				if(!empty($oBuyer))
				{
					$o['buyer_username'] = $oBuyer['username'];
					$o['buyer_nickname'] = $oBuyer['nickname'];
					$buyer_usertype = $oBuyer['usertype'];
					
				}
			}

			if($buyer_usertype==1)
			{
				$res['code'] = 202;
				$res['data']['error_messages'] = array('模特不能预约其他模特');
				return $res;
			}

			$oBook['begtime'] = strtotime($begtime);
			if($oBook['time']==1)	//时间:天
			{
				$oBook['endtime'] = $oBook['begtime'] + 24*60*60*($num-1);
			}
			else if($oBook['time']==2)	//时
			{
				if(date('H',$oBook['begtime'])=='00')
					$oBook['begtime'] = strtotime($begtime)+8*60*60;
				$oBook['endtime'] = $oBook['begtime'] + 60*60*$num;
			}
			else 
			{
				//默认为一天
				$oBook['endtime'] = $oBook['begtime'] + 8*60*60;
			}
                        
			$o['totalprice'] = $oBook['price'] * $oBook['num'];
                        if($oBook['time'] == 5) {
                            //处理面谈
                            $o['totalprice'] = 0;
                        }
                        
                        
			$orderid = $this->ci->Order_model->insert_string($o);
			$oBook['orderid'] = $orderid;
			$time_zone = $this->ci->input->post('time_zone');
			//时间区间
			//上午
			if ($time_zone == 1)
			{
			    $oBook['endtime'] = $oBook['begtime'];
			}
			//下午
			elseif ($time_zone == 2)
			{
			    $oBook['begtime'] = $oBook['begtime'];
			    $oBook['endtime'] = $oBook['begtime'];
			}
			//晚上
			elseif ($time_zone == 3)
			{
			    $oBook['begtime'] = $oBook['begtime'];
			    $oBook['endtime'] = $oBook['begtime'];
			}
			//全天
			else 
			{
			    $endtime = $this->ci->input->post('endtime');
			    $oBook['endtime'] = strtotime($endtime);
			}
			$oBook['time_zone'] = $time_zone;
			$outerid = $this->ci->Orderbook_model->insert_string($oBook);
			$this->ci->Order_model->update_by_id($orderid, array('outerid'=>$outerid));
			//统计订单数与新订单数
			//判断sellerid，如属于某个机构旗下的艺人则反馈到这个结构下
			if ($oSeller['insid'])
			    $sellerid = $oSeller['insid'];
			$this->ci->load->service('num_service');
			$this->ci->num_service->set_user_num($sellerid,'be_ordernum');
			$this->ci->num_service->set_user_num($buyerid,'ordernum');
			$this->ci->num_service->set_user_num($sellerid,'be_ordernum_new',1);
			$this->ci->num_service->set_user_num($buyerid,'be_ordernum_new',1);
			$this->ci->num_service->set_user_num($buyerid,'ordernum_new',1);
			$this->ci->num_service->set_user_num($sellerid,'be_ordernum_m');
			$this->ci->num_service->set_user_num($buyerid,'ordernum_m');
			$this->ci->num_service->set_user_num($sellerid,'be_fund_m');
			$this->ci->num_service->set_user_num($buyerid,'fund_m');
            //今日下单次数
			$this->ci->num_service->set_user_num($sellerid,'be_ordernum_t');
			$this->ci->num_service->set_user_num($buyerid,'ordernum_t');

			//发送下订单短信
			$this->ci->load->library('sms');
			$sms = "尊敬的魔步网用户恭喜您收到一份工作订单，请于4小时内登录反馈，逾期订单将失效。详情联系客户".$this->ci->input->post('linkway');
			if ($oSeller)
			{
				$mobile = $oSeller["mobile"];
				if ($oSeller['insid'])
				{
					$ins_user = $this->ci->User_model->get_by_id($oSeller['insid']);
					if ($ins_user && $ins_user['mobile'])
					{
						$mobile = $ins_user['mobile'];
					}
				}
				if ($mobile)
				{
					$this->ci->sms->sendMess(array($mobile), $sms);
				}
			}
			
			//占库存（模特、艺人档期）
			$this->ci->load->model('Orderbook_model');
			$orderbook = $this->ci->Orderbook_model->get_by_where(array('no'=>$no));
			if ($orderbook)
			{
				$this->ci->load->model('Schedule_model');
				$data = array();
				$data['no'] = $no;
				$data['userid'] = $o['sellerid'];
				$data['dodate'] = $orderbook['begtime'];
				$data['enddate'] = $orderbook['endtime'];
				$data['thing'] = $o['title'];
				$data['type'] = 1;
				$data['addtime'] = time();
				$data['op_userid'] = $o['buyerid'];
				$data['op_username'] = $o['buyer_username'];
				$data['op_time'] = $o['addtime'];
				$data['status'] = 1;
				$data['time_zone'] = $time_zone;
				$this->ci->Schedule_model->insert($data);
			}
			
			$res['code'] = 200;
		}
		else
		{
			$res['data']['error_messages'] = $this->ci->form_validation->getErrors();
		}

		return $res;

	}

	//订单过期处理（超过4小时，自动关闭未确认的订单；超过1小时，自动关闭确认后但未支付的订单）
	public function expiredOrder()
	{
		$this->ci->load->model('Order_model');
		//超过12小时关闭未确认的订单
		$norejectOrders = $this->ci->Order_model->list_by_where(array('addtime <'=>(time()-4*60*60),'paystatus'=>0,'status'=>1,'reject'=>array(0)),'no');
		$this->ci->Order_model->update_by_where(array('addtime <'=>(time()-4*60*60),'paystatus'=>0,'status'=>1,'reject'=>0 ),array('paystatus'=>3) );
		
		//超过1小时关闭已确认但未支付的订单
		$orders = $this->ci->Order_model->list_by_where(array('addtime <'=>(time()-1*60*60),'paystatus'=>0,'status'=>1,'reject'=>1),'no');
		$orders = array_merge($orders,$norejectOrders);
		$no_arr = array();
		if ($orders)
		{
			foreach ($orders as $key=>$val)
			{
				array_push($no_arr,$val['no']);
			}
		}
		//删除已占的库存
		if ($no_arr)
		{
			$this->ci->load->model('Schedule_model');
			$this->ci->Schedule_model->update_by_where(array('no'=>$no_arr, 'status'=>1),array('status'=>0));
		}
		$this->ci->Order_model->update_by_where(array('addtime <'=>(time()-1*60*60),'paystatus'=>0,'status'=>1,'reject'=>array(1) ),array('paystatus'=>3) );
		
	}
	
	//订单过期提前十分钟发送短信
	public function expireOrderMsm()
	{
	    $this->ci->load->model('Order_model');
	    //超过4小时关闭未确认的订单
	    $norejectOrders = $this->ci->Order_model->list_by_where(array('addtime <='=>(time()-4*60*60+10*60),'addtime >'=>(time()-4*60*60),'paystatus'=>0,'status'=>1,'smsflag'=>0,'reject'=>array(0)),'buyer_username,seller_username,sellerid,id');
// 	    echo $this->ci->Order_model->db->last_query();die;
	    //超过1小时关闭已确认但未支付的订单
	    $orders = $this->ci->Order_model->list_by_where(array('addtime <='=>(time()-1*60*60+10*60),'addtime >'=>(time()-1*60*60),'paystatus'=>0,'status'=>1,'reject'=>1,'smsflag'=>0),'buyer_username,seller_username,sellerid,id');
	    $orders = array_merge($orders,$norejectOrders);
	    
	    //订单过期发送短信
	    if ($orders)
	    {
	        $this->ci->load->library('sms');
	        $sms = "天哪？您在魔步网的订单居然还没有处理，再过10分钟就过期了，速去速去！——魔步网小二提醒！";
	        foreach ($orders as $val)
	        {
	            $mobile_arr = array();
	            //下单人号码
	            $buyer_username = $val['buyer_username'];
	            if ($buyer_username && is_mobile($buyer_username))
	            {
	                array_push($mobile_arr, $buyer_username);
	            }
	            //被下单人号码
	            $seller_username = $val['seller_username'];
	            if ($seller_username)
	            {
	                if (is_mobile($seller_username))
	                {
	                    array_push($mobile_arr, $seller_username);
	                }
	                else
	                {
	                    //如是机构旗下艺人，对机构发送短信
	                    $sellerid = $val['sellerid'];
	                    $this->ci->load->model('User_model');
	                    $sellerModel = $this->ci->User_model->get_by_id($sellerid,'insid');
	                    if ($sellerModel && $sellerModel['insid'])
	                    {
	                        $insModel = $this->ci->User_model->get_by_id($sellerModel['insid'],'username');
	                        if ($insModel && $insModel['username'])
	                        {
	                            array_push($mobile_arr, $insModel['username']);
	                        }
	                    }
	                }
	            }
	            $this->ci->sms->sendMess($mobile_arr, $sms);
	        }
	        
	        //修改订单表短信发送状态
	        $ids = array_map('end', $orders);
	        $this->ci->Order_model->update_by_where(array('id'=>$ids),array('smsflag'=>1));
	    }
	}
}